import re
import json
import urllib3
import urllib.parse
from Resp import Resp

urllib3.disable_warnings()

AppKey = '<AppKey>'
SecretKey = '<SecretKey>'

def getLoginCode():
    http = urllib3.PoolManager(cert_reqs='CERT_NONE')
    try:
        resp = http.request(
            'GET', 'http://openapi.baidu.com/oauth/2.0/device/code?response_type=device_code&client_id=' + AppKey + '&scope=basic,netdisk')
        print(resp.data.decode())
        return resp.data.decode()
    except urllib3.exceptions.HTTPError as e:
        print(e)
        return None


def checkLoginStatus(deviceCode):
    http = urllib3.PoolManager(cert_reqs='CERT_NONE')
    try:
        resp = http.request(
            'GET', 'https://openapi.baidu.com/oauth/2.0/token?grant_type=device_token&code=' +
            deviceCode + '&client_id=' + AppKey + '&client_secret=' + SecretKey)
        print(resp.data)
        print(resp.data.decode())
        return resp.data.decode()
    except urllib3.exceptions.HTTPError as e:
        print(e)
        return None


def filelist(access_token, path):
    print('access_token = ' + access_token + '  path = ' + path)
    http = urllib3.PoolManager(cert_reqs='CERT_NONE')
    headers = {"Host": "pan.baidu.com"}
    try:
        resp = http.request(
            'GET', 'https://pan.baidu.com/rest/2.0/xpan/file?method=list&access_token=' + access_token + "&dir=" + urllib.parse.quote(path), headers=headers)
        return Resp.success(resp.data.decode())
    except urllib3.exceptions.HTTPError as e:
        print(e)
        return Resp.fail("失败")


def getm3u8(access_token, path, type, adToken):
    types = ["M3U8_AUTO_480", "M3U8_AUTO_720", "M3U8_AUTO_1080"]

    http = urllib3.PoolManager(cert_reqs='CERT_NONE')
    headers = {"Host": "pan.baidu.com",
               "User-Agent": "xpanvideo;netdisk;iPhone13;ios-iphone;15.1;ts"}
    try:
        if adToken != None:
            resp = http.request(
                'GET', 'https://pan.baidu.com/rest/2.0/xpan/file?method=streaming&access_token=' + access_token + "&path=" + urllib.parse.quote(path) + "&type=" + types[type] + '&adToken=' +  urllib.parse.quote(adToken), headers=headers)
        else:
            resp = http.request(
                'GET', 'https://pan.baidu.com/rest/2.0/xpan/file?method=streaming&access_token=' + access_token + "&path=" + urllib.parse.quote(path) + "&type=" + types[type], headers=headers)
        print(resp.headers['Content-Type'])
        contentType = resp.headers['Content-Type']
        if contentType != 'application/x-mpegURL':
            return Resp.fail(json.loads(resp.data.decode()))
        return Resp.success(resp.data.decode())
    except urllib3.exceptions.HTTPError as e:
        print(e)
        return None

def getTotalTime(content):
    a = r'EXTINF:(.*?),'
    try:
        slotList = re.findall(a, content)
        tot = 0
        for v in slotList:
            tot += int(v)
        return tot
    except:
        return None
